// pages/room/index.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        openid: "",
        room_items: [],
    },
    toMessage(e){
        let _id = e.currentTarget.dataset.id
        let url = `/pages/message/index?room_id=${_id}`
        wx.navigateTo({
          url: url,
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // let _this = this
        let app = getApp()
        console.log(app.globalData)
        console.log(app.globalData.openid)
        this.data.openid = app.globalData.openid
        console.log(this)
    },

    change_room_items: async (room_items, openid) => {
        let _this = this
        console.log(room_items)
        console.log(openid)
        let arr = []
        for (let item of room_items) {
            let user_id = ""
            if (item.sender[0] == openid) {
                user_id = item.sender[1]
            } else {
                user_id = item.sender[0]
            }
            arr.push(
                wx.cloud.database().collection("info").where({
                    _openid: user_id
                }).get().then((res) => {
                    // console.log(res)
                    return res
                })
            )
            // Promise.all(arr).then
        }
        return Promise.all(arr)
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        if (this.data.openid == "") {
            let app = getApp()
            this.data.openid = app.globalData.openid
        }
        let _this = this
        console.log(this.data)
        const _ = wx.cloud.database().command
        let watch = wx.cloud.database().collection("room").where({
            sender: _.elemMatch(_.eq(_this.data.openid))
        }).watch({
            onChange: (snapshot) => { //只要数据发生变化就会调用此方法
                console.log(snapshot)
                // let rooms = _this.data.room_items
                let rooms = snapshot.docs

                _this.change_room_items(rooms, _this.data.openid).then((res) => {
                    for (let index = 0; index < rooms.length; index++) {
                        rooms[index].contact = res[index].data[0]
                    }
                    _this.setData({
                        room_items: rooms,
                    })
                }).then((res) => {
                    console.log(_this.data.room_items)
                })



            },
            onError: function (err) {
                console.error('the watch closed because of error', err)
            }
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})